package com.cse.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cse.constants.SystemConstants;
import com.cse.dto.Result;
import com.cse.dto.ScrollResult;
import com.cse.dto.UserDTO;
import com.cse.entity.Blog;
import com.cse.entity.Follow;
import com.cse.entity.User;
import com.cse.mapper.BlogMapper;
import com.cse.service.IBlogService;
import com.cse.service.IFollowService;
import com.cse.service.IUserService;
import com.cse.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static com.cse.constants.RedisConstants.BLOG_LIKED_KEY;
import static com.cse.constants.RedisConstants.FEED_KEY;
import static com.cse.constants.SystemConstants.BLOG_NULL;
import static com.cse.constants.SystemConstants.PUSH_BLOG_ERROR;


@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IFollowService followService;



    @Override
    public Result saveBlog(Blog blog) {
                // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean success = save(blog);
        if (!success) {
            return Result.fail(PUSH_BLOG_ERROR);
        }
        //查询笔记作者的所有粉丝 select * from tb_follow where follow_id=?
        List<Follow> follows =
                followService.query()
                        .eq("follow_user_id", user.getId().toString()).list();
        //推送笔记id给所有粉丝
        for (Follow follow : follows) {
            Long userId = follow.getUserId();
            //推送
            String key=FEED_KEY+userId;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());

    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key=BLOG_LIKED_KEY+id;
        //1查寻top5的点赞用户
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        //2解析出用胡
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        //3查询用户
        String idStr= StrUtil.join(",",ids);
        List<UserDTO> userDTOs = userService.query()
                .in("id",ids)
                .last("ORDER BY FIELD(id,"+idStr+")").list()
                .stream()
                .map(user -> BeanUtil
                .copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOs);
    }

    @Override
    public Result likeBlog(Long id) {
        //1获取登录用户
        Long userid = UserHolder.getUser().getId();
        //2判断当前用户是否已经点赞
        String key=BLOG_LIKED_KEY+id;
        //判断元素是否是集合set的成员
        Double score = stringRedisTemplate.opsForZSet().score(key, userid.toString());
        //3如果未点赞，可以点赞
        if (score == null) {
            //3.1数据库点赞加1
            boolean isSuccess=update().setSql("liked=liked+1").eq("id",id).update();
            if (isSuccess) {
                //3.2保存用户到redis的zset集合 score为时间戳
                stringRedisTemplate.opsForZSet().add(key,userid.toString(),System.currentTimeMillis());
            }
            //4如果已点赞，取消点赞
        }else{
            //4.1数据库点赞减1
            boolean isSuccess=update().setSql("liked=liked-1").eq("id",id).update();
            //4.2从redis的set集合中移除用户
            stringRedisTemplate.opsForZSet().remove(key,userid.toString());
        }
        return Result.ok();
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog->{
            this.queryBlogUser(blog);
            isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        //1.查询blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail(BLOG_NULL);
        }
        queryBlogUser(blog);
        //查询blog是否被点赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        UserDTO user=UserHolder.getUser();
        if (user==null){
            return;
        }
        //1获取登录用户
        Long userid = user.getId();
        //2判断当前用户是否已经点赞
        String key=BLOG_LIKED_KEY+blog.getId();
        //判断元素是否是集合set的成员
        Double score = stringRedisTemplate.opsForZSet().score(key, userid.toString());
        blog.setIsLike(score != null);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2.查询收件箱 ZREVRANGEBYSCORE key Max Min LIMIT offset count
        String key=FEED_KEY+userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples =
                stringRedisTemplate.opsForZSet().
                        reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if(typedTuples==null||typedTuples.isEmpty()){
            return Result.ok();
        }
        //3.解析数据：blogId,minTime时间戳，offset
        List<Long> ids=new ArrayList<>(typedTuples.size());
        long minTime=0;
        int os=1;
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            //获取id
            ids.add(Long.valueOf(tuple.getValue()));
            //获取时间戳
            long time = tuple.getScore().longValue();
            if (time==minTime) {
                os++;
            }else {
                minTime=time;
                os=1;
            }
            minTime = time;

        }
        //4.根据blogId查询blog
        String idStr=StrUtil.join(",",ids);
        List<Blog> blog=query().in("id",ids).last("ORDER BY FIELD(id,"+idStr+")").list();
        for (Blog blog1 : blog) {
            //查询blog有关的人
            queryBlogUser(blog1);
            //是否被点赞
            isBlogLiked(blog1);
        }
        //5.封装返回
        ScrollResult r=new ScrollResult();
        r.setList(blog);
        r.setOffset(os);
        r.setMinTime(minTime);
        return Result.ok(r);
    }
}

